package FenxiaoService

import (
	"context"
	"gdshop-font-api-go/app/response/FenxiaoResp"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"gdshop-font-api-go/library/tools/myCache"
	"gdshop-font-api-go/library/tools/mylog"
	"github.com/gogf/gf/util/gconv"
	"time"
)

var fenxiaoConfigKey = "fenxiao"

func GetConfig() (*FenxiaoResp.GetConfig, error) {
	var data *FenxiaoResp.GetConfig
	value, err := myCache.GetOrSetFunc("sys_config:"+fenxiaoConfigKey, func() (interface{}, error) {
		nei, err := toolsDb.GetUnSafaTableAddDeleteWhere(context.Background(), "sys_config").Where(
			"config_key = ?", fenxiaoConfigKey).Value("config_value")
		if err != nil {
			return data, err
		}
		return nei.String(), nil
	}, 86400*time.Second)
	if err != nil {
		return nil, err
	}
	err = gconv.Scan(value, &data)
	if err != nil {
		return nil, err
	}
	return data, nil
}

// 配置 是否开启分销
// true 开启状态
func ConfigLevelConfig() bool {
	/*count, err := toolsDb.GetUnSafaTableAddDeleteWhere(context.Background(), "sys_config").Where(
		"config_key = ? AND config_value->'$.level_config' = 1", fenxiaoConfigKey).Count()
	if err != nil {
		return false
	}
	return count > 0*/

	config, err := GetConfig()
	if err != nil {
		mylog.ErrorLog("ConfigLevelConfig " + err.Error())
		return false
	}

	return config.LevelConfig == 1
}

// 配置 开启自购分佣，并且 开启分销
// true 开启状态
func ConfigSelfPurchaseRebate() bool {
	/*count, err := toolsDb.GetUnSafaTableAddDeleteWhere(context.Background(), "sys_config").Where(
		"config_key = ? AND config_value->'$.level_config' = 1 AND config_value->'$.self_purchase_rebate' = 1", fenxiaoConfigKey).Count()
	if err != nil {
		return false
	}
	return count > 0*/

	config, err := GetConfig()
	if err != nil {
		return false
	}

	return config.LevelConfig == 1 && config.SelfPurchaseRebate == 1
}
